<template>
	<view class="custom-tour">
		<basic-nav-bar 
			backgroundColor="transparent"
			color="#ffffff"
			:statusBar="true"
			:border="false"
			left-icon="arrowleft"/>
		<img class="header-image" src="https://imgs.bestwehotel.com/images/inn/1bqD50FTcx" alt="">
		<view class="content">
			<view class="tabs">
				<view class="tab" :class="{active: tabIndex == item.value}" v-for="item in tabs" :key="item.value" @click="changeTab(item.value)">
					{{item.name}}
				</view>				  
			</view>
			<view class="form--wrap">
				<u-form :error-type="formErrorType" :model="form" ref="customForm" label-width="200rpx" :label-style="labelStyle">
					<view class="departure-destination u-border-bottom" >
						<u-form-item prop="city" :border-bottom="false">
							<u-input v-model="form.departure" disabled placeholder="出发地" input-align="left" :custom-style="areaStyle" @click="goChooseCity(1)"/>
						</u-form-item>
						
						<img src="https://imgs.bestwehotel.com/images/inn/1bqrKXNQxy" style="width:40rpx;height:40rpx;" />

						<u-form-item prop="city" :border-bottom="false">
							<u-input v-model="form.destination" disabled placeholder="目的地" input-align="right" :custom-style="areaStyle" @click="goChooseCity(2)"/>
						</u-form-item>
					</view>
					
					<u-form-item label="出行时间" prop="startDate">
						<u-input v-model="dateRange" placeholder="请选择出行时间" disabled @click="showCalendar=true" />
					</u-form-item>
					<u-form-item label="出行人数" prop="travelers">
						<u-input v-model="form.travelers" placeholder="请选择出行人数" disabled @click="showNumberPopover = true"/>
					</u-form-item>
					<u-form-item label="人均预算" prop="averageBudget">
						<view class="dudget-content">
							<text v-if="form.averageBudget">￥</text>
							<u-input v-model="form.averageBudget" :custom-style="{flex:'1','flex-basis': '0%'}" placeholder="请填写您的预算" />
						</view>
					</u-form-item>
					<u-form-item label="联系人" prop="contactName">
						<u-input v-model="form.contactName" placeholder="请填写您的姓名" />
					</u-form-item>
					<u-form-item label="联系电话" prop="contactMobile">
						<u-input v-model="form.contactMobile" placeholder="请填写您的联系电话" maxlength="11"/>
					</u-form-item>
					<u-form-item v-if="tabIndex==2" label="公司名称" prop="companyName">
						<u-input v-model="form.companyName" placeholder="请填写公司名称"/>
					</u-form-item>
				</u-form>					
				<view class="bt" >
						<basic-button type="primary" borderRadius="44rpx" width="622rpx" height='88rpx' @click="onSubmit">获取专属定制</basic-button>	  
				</view>		  
			</view>
			<view class="custom-my-card" @click="goOrderList">
				<image src="https://imgs.bestwehotel.com/images/inn/1bqsbKRbB8" style="width:52rpx;height:52rpx" /> 
				<view class="text">查看我的定制</view>	
				<view>
						<basic-icons name="icon-arrow-right" size="30rpx" color="#1B2431" />					  
				</view>			  
			</view>
			<view class="custom-intro-card" @click="goIntro">
				<view class="custom-intro-title">锦江wehotel定制游</view>
				<view class="custom-intro-content">
					<view
						v-for="(introItem, index) in introList"
						:key="index"
						class="card-intro-item">
						<view class="card-icon-wrapper">
							<basic-icons :name="introItem.icon" size="52rpx"></basic-icons>
						</view>

						<view class="card-intro-desc">{{introItem.desc}}</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 日历 -->
		<u-calendar
		mode="range"
		safe-area-inset-bottom
		v-model="showCalendar"
		active-bg-color="#00CBD6"
		range-color="#00CBD6"
		range-bg-color="rgba(0,203,214,0.13)"
		:min-date="today"
		:max-date="lastSelectableDate"
		@change="dateChange"></u-calendar>

		<!-- 出行人数 -->
		<basic-bottom-popover v-model="showNumberPopover" :title="popoverTitle">
			<template v-if="tabIndex === 1">
				<view class="number-box-row border-bottom">
					<view class="number-box-content">成人</view>
					<view class="number-box-stepper">
						<u-number-box v-model="popoverAdultNum" :min="0" color="#00CBD6"/>
					</view>
				</view>
				<view class="number-box-row">
					<view class="number-box-content">儿童</view>
					<view class="number-box-stepper">
						<u-number-box v-model="popoverChildrenNum" :min="0" color="#00CBD6"/>
					</view>
				</view>
			</template>

			<!-- 出行人数范围 -->
			<picker-view 
				v-else-if="tabIndex === 2" 
				indicator-class="selector-indicator" 
				class="selector"
				v-model="popoverTravelerIndex"
				@change="onTravelerPickerChange">
				<picker-view-column>
					<view v-for="(item, index) in travelersRangeList" :key="index" class="selector-item">{{item}}</view>
				</picker-view-column>
			</picker-view>			

			<view class="number-box-btn-wrapper">
				<basic-button type="plain" border width="304rpx" heght="72rpx" @click="cancelNumber">取消</basic-button>
				<basic-button width="304rpx" heght="72rpx" @click="updateTravelers">确定</basic-button>
			</view>

			<basic-safe-area></basic-safe-area>
		</basic-bottom-popover>
		<!-- 提交成功弹框 -->
		<uni-popup ref="successPopup" type="center" >
			<view class="success-dialog--wrap">
				<view>
				<image class="image" src="https://imgs.bestwehotel.com/images/inn/1btC0wZ1Gc">             
				</view>
				<view class="title">提交成功!</view> 
				<view class="subtitle">稍后会有旅行定制师与您联系～</view> 
				<basic-button class="bt" @click="successOK" width="280rpx" height="64rpx">好的</basic-button> 
			</view>
		</uni-popup>
	</view>
</template>
<script>
import city from '@/mixins/city'
import sdk from 'sdk'
import {createCustomOrder, getUserInfo} from 'api'
import {dateFormat} from 'utils/helper/date-handle'
export default {
	name: 'custom-tour',
	mixins: [city],
	data() {
		return {
			showCalendar: false,
			showNumberPopover: false,
			showNumberRangePopover: false,

			today: dateFormat(),
			lastSelectableDate: dateFormat(Date.now() + 31536000000), // 一年之内可选

			tabIndex: 1,
			areaStyle: {
				'font-size': '36rpx',
				'color': '#1B2431'
			},
			labelStyle: {
				'font-size': '28rpx',
				'color': '#1B2431'
			},
			tabs: [
				{
					name: '个人定制',
					value: 1
				},{
					name: '公司定制',
					value: 2
				},
			],

			travelersRangeList: ['0-10人', '10-20人', '20-30人', '30-40人', '40-50人', '50人以上'],

			// cityError: false, // 出发地目的地校验失败
			dateRange: '', // 出行时间
			popoverAdultNum: 0,
			popoverChildrenNum: 0,
			popoverTravelerIndex: [-1], // 出行人数范围

			form: {
				departure: '',
				destination: '',
				startDate: '',
				returnDate: '',
				travelers: '', // 出行人数字符串
				adultNum: 0,
				childrenNum: 0,
				contactMobile: '',
				contactName: '',
				companyName: '',
				averageBudget: ''
			},

			// 表单校验规则
			validatePass: false, // 标记表单提交之前是否通过表单校验（处理提交过程中的登录）
			formErrorType: [/* 'border-bottom' */, 'toast'],
			rules: {
				city: [{
					validator: (rule, value, callback) => {
						if (!this.form.departure) {
							// this.cityError = true
							callback(new Error('请选择出发地'))
						} else if (!this.form.destination) {
							// this.cityError = true
							callback(new Error('请选择目的地'))
						} else {
							// this.cityError = false
							return true
						}
					},
					trigger: ['change']
				}],
				startDate: [{ required: true, message: '请选出行时间' }],
				returnDate: [{ required: true, message: '请选出行时间' }],
				travelers: [{ required: true, message: '请选择出行人数' }],
				averageBudget: [
					{ required: true, message: '请填写您的预算' },
					{
						validator: (rule, value, callback) => {
							return this.$u.test.digits(value)
						},
						message: '预算必须为正整数'
					},
				],
				contactName: [{ required: true, message: '请填写您的姓名' }],
				companyName: [{ required: true, message: '请填写公司名称' }],
				contactMobile: [{
					required: true, 
					message: '请填写您的联系电话'
				}, {
					validator: (rule, value, callback) => {
						return this.$u.test.mobile(value)
					},
					message: '联系电话请填写手机号码'
				}]
			},

			selectCityType: 0, // 标记是否已进入城市选择页面 0：未选择 1:出发城市  2：旅游城市
			
			introList: [
				{icon: 'icon150', desc: '免费咨询'},
				{icon: 'icon149', desc: '1v1定制'},
				{icon: 'icon104', desc: '省心好玩'},
				{icon: 'icon92', desc: '专业高效'}
			]
		}
	},

	computed: {
		hasLogin() {
			return this.$store.state.login.hasLogin
		},
		popoverTitle() {
			return this.tabIndex===1 ? '选择人数' : '选择出游人数范围'
		}
	},

	watch: {
		hasLogin(val, oldVal) {
			// 登录完重新提交接口
			if(val && !oldVal) {
				// 排除掉野蛮初始化的登录状态变更
				this.validatePass && this.onSubmit()

				// 初始化手机号码
				this.getUserInfo()
			}
		}
	},

	onShow() {
		this.checkSelectedCity()		
	},

	onLoad() {
		this.getLocationCity()

		if (this.hasLogin) {
			this.getUserInfo()
		}
	},

	onReady() {
		this.setFormRule()				
	},

	methods: {
		getUserInfo() {
			getUserInfo().then(res => {
				let {mobile} = res.result || {}
				
				if (mobile){
					this.form.contactMobile = mobile
				}
			})
		},
		getLocationCity() {
			this.$city_getLocation().then(res => {
				this.form.departure = res.city
			})
		},
		resetFormData() {
			// [bug] resetFields方法在小程序中无效
			// this.$refs.customForm.resetFields()
			this.validatePass = false
			this.form.departure = ''
			this.form.destination = ''
			this.form.startDate = ''
			this.form.returnDate = ''
			this.form.travelers = ''
			this.form.adultNum = 0
			this.form.childrenNum = 0
			this.form.contactMobile = ''
			this.form.contactName = ''
			this.form.companyName = ''
			this.form.averageBudget = ''
			this.popoverAdultNum = 0
			this.popoverChildrenNum = 0
			this.popoverTravelerIndex = [-1]
			this.dateRange = ''
		},
		setFormRule() {
			// 重置校验规则
			let {city, startDate, returnDate, travelers, averageBudget, contactName, contactMobile, companyName} = this.rules

			let rules = {}
			if (this.tabIndex === 1) {
				rules = {city, startDate, returnDate, travelers, averageBudget, contactName, contactMobile}
			} else if (this.tabIndex === 2) {
				rules = {city, startDate, returnDate, travelers, averageBudget, contactName, contactMobile, companyName}
			}

			this.$refs.customForm.setRules(rules)
		},
		checkSelectedCity() {
			if (!this.selectCityType) return

			sdk.getSelectCity().then(res => {
				if (!res.name) return // 未选中任何城市

				let { name } = res
				
				switch(this.selectCityType) {
					case 1: 
						this.form.departure = name
						break
					case 2: 
						this.form.destination = name
						break
				}

				this.selectCityType = 0

				// 防止干扰到其它模块的城市选择
				sdk.selectCity({})
			})
		},
		changeTab(value) {
			this.tabIndex = value

			// 修改出行人数
			this.updateTravelers()

			this.setFormRule()
		},
		onTravelerPickerChange(e) {
			this.popoverTravelerIndex = e.detail.value
		},
		dateChange(res) {
			this.form.startDate = res.startDate
			this.form.returnDate = res.endDate
			this.dateRange = `${res.startDate} 至 ${res.endDate}`
		},
		/**
		 * 选择城市 type 1:出发城市  2：旅游城市
		 */
		goChooseCity(type) {
			switch(type) {
				case 1: 
					sdk.navigateTo({
						url: '/pages/select-city/index?productType=-1&location=1'
					})
					this.selectCityType = 1
					break
				case 2: 
					sdk.navigateTo({
						url: '/pages/select-city/index?productType=-1&hot=1'
					})
					this.selectCityType = 2
					break
			}
		},
		cancelNumber() {
			this.showNumberPopover = false

			switch(this.tabIndex) {
				case 1: 
					this.popoverAdultNum = this.form.adultNum
					this.popoverChildrenNum = this.form.childrenNum
					break
				case 2: 
					this.popoverTravelerIndex = [this.travelersRangeList.indexOf(this.form.travelers)]
					break
			}
		},
		updateTravelers() {
			this.showNumberPopover = false

			switch(this.tabIndex) {
				case 1: 
					this.form.adultNum = this.popoverAdultNum
					this.form.childrenNum = this.popoverChildrenNum
					let travelers = []
					if (this.form.adultNum) {
						travelers.push(`成人 × ${this.form.adultNum}`) 
					}

					if (this.form.childrenNum) {
						travelers.push(`儿童 × ${this.form.childrenNum}`) 
					}

					this.form.travelers = travelers.join('，')
					break
				case 2: 
					this.form.travelers = this.travelersRangeList[this.popoverTravelerIndex[0]]
					break
			}
			
		},
		onSubmit() {
			this.$refs.customForm.validate((valid) => {
				if (valid) {
					this.validatePass = true
					let params = {
						departure: this.form.departure,
						destination: this.form.destination,
						startDate: this.form.startDate,
						returnDate: this.form.returnDate,
						contactMobile: this.form.contactMobile,
						contactName: this.form.contactName,
						companyName: this.form.companyName,
						averageBudget: Math.floor(Number(this.form.averageBudget))
					}

					switch(this.tabIndex) {
						case 1: 
							params.type = 0
							params.adultNum = this.form.adultNum
							params.childrenNum = this.form.childrenNum
							break
						case 2: 
							params.type = 1
							params.companyAdultNum = this.form.travelers
							break
					}
					sdk.showLoading({mask: true})
					createCustomOrder(params).then(res => {
						sdk.hideLoading()
						// 弹框提示提交成功
						this.$refs.successPopup.open()
					}).catch(_ => {})
				} else {
					this.validatePass = false
				}
			})
		},
		goOrderList() {
			sdk.navigateTo({
				url: '/packageOrder/pages/custom-order/index'
			})
		},
		goIntro() {
			sdk.navigateTo({
				url: '/packageDetail/pages/custom-intro/index'
			})
		},
		successOK() {
			this.$refs.successPopup.close()
			this.resetFormData()
			// 初始化城市
			this.getLocationCity()
			// 初始化手机号
			this.getUserInfo()
		}
	}
}
</script>
<style lang="less">
.custom-tour{
	position: relative;
	// background: url('https://imgs.bestwehotel.com/images/inn/1bqD50FTcx');
	// background-size: 750rpx 392rpx;
	// background-repeat: no-repeat;
	.header-image {
		width: 100%;
		height: 392rpx;
		position: absolute;
		top: 0;
		z-index: -1;
	}
	.content{
		position: absolute;
		top: 302rpx;
		
		display: flex;
		justify-content: center;
		flex-direction: column;

		width: 100%;
		padding: 0 30rpx 25rpx;

		.custom-my-card {
			width: 100%;
			height: 112rpx;	

			.flex;
			.flex-middle;

			font-size: 28rpx;
			font-weight: 600;
			
			background: #FFFFFF;
			box-shadow: 0px 4rpx 60rpx 0px rgba(0, 0, 0, 0.04);
			border-radius: 16rpx;
			
			margin: 30rpx 0;
			padding: 40rpx;

			.text{
				margin: 0 4rpx 0 16rpx;
			}
		}
		
		.custom-intro-card {			
			color: #1B2431;
			background: #FFFFFF;
			box-shadow: 0px 4rpx 60rpx 0px rgba(0, 0, 0, 0.04);
			border-radius: 16rpx;
			padding: 40rpx;

			.custom-intro-title {
				font-weight: 600;
			}

			.card-intro-item {
				.flex;
				.flex-middle;
				.flex-column;
			}

			.custom-intro-content {
				.flex;
				.flex-between;

				margin-top: 32rpx;
			}

			.card-icon-wrapper {
				.flex;
				.flex-middle;
				.flex-center;

				width: 100rpx;
				height: 100rpx;
				color: @theme_color;
				background: fade(@theme_color, 4%);
				border-radius: 100%;
			}

			.card-intro-desc {
				font-size: 24rpx;
				color: @font_desc_color;
				text-align: center;
				margin-top: 8rpx;
			}
		}
		.tabs{
			display: flex;

			margin-bottom: -2rpx;
			.tab{
				width: 192rpx;
				height: 72rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: rgba(0, 0, 0, 0.49);
				color: #fff;
				font-size: 28rpx;				
				border-radius: 16rpx 16rpx 0 0;

				margin-right: 26rpx;

				&.active{
					background: #fff;
					color: #1B2431;
				}
			}
		}
		.form--wrap{
			background: #fff;			
			box-shadow: 0 4rpx 60rpx 0 rgba(0, 0, 0, 0.04);
			border-radius: 0 16rpx 16rpx 16rpx;
			padding: 30rpx;

			.departure-destination {
				.flex;
				.flex-middle;

				font-weight: 600;

				&.u-border-bottom.error:after {
					border-color: #fa3534; // 和uView保持一致
				}
			}
			.bt{
				margin-top: 34rpx;
			}

			.dudget-content {
				.flex;
				.flex-middle;
			}
		}
	}

	.number-box-row {
		.flex;
		.flex-middle;
		.flex-between;

		margin: 0 30rpx;
		height: 112rpx;

		&.border-bottom {
			border-bottom: 1rpx solid @border_color;
		}

		.sku-content {
			.flex-1;
		}
	}

	.number-box-btn-wrapper {
		.flex;
		.flex-middle;
		.flex-between;

		padding: 0 30rpx;
		height: 130rpx;
		border-top: 1rpx solid @border_color;
	}

	@selector__row_height: 80rpx;
	@selector_height: 442rpx;

	/deep/ .u-calendar__content__bg-month {
		opacity: 0;
	}
	
	/deep/ .selector {
		width: 100%;
		height: @selector_height;
	}

	/deep/ .selector-item {
		height: @selector__row_height;
		line-height: @selector__row_height;
		text-align: center;
	}

	/deep/ .selector-indicator {
		height: @selector__row_height;
	}

	.success-dialog--wrap{
		.flex;
		.flex-column;
		.flex-center;
		.flex-middle;

		width: 520rpx;
		height: 610rpx;
		border-radius:16rpx;
		background: #fff;
		.image{
			width: 168rpx;
			height: 168rpx;
		}
		.title{			
			font-size: 32rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #1B2431;
			margin: 30rpx 0 20rpx;
		}
		.subtitle{			
			font-size: 24rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #000000;
			margin-bottom: 94rpx
		}
	}
}
</style>